<?php

App::import("Component", "Captcha");

class HomesController extends AppController {

    var $name = 'Homes';
    var $uses = array('User', 'Subject', 'SubjectRate', 'Facts', 'Tag');

    function beforeFilter() {
        parent::beforeFilter();
        // echo $this->Session->setFlash("Welcome user");
        $this->Auth->userScope = array('User.role =' => 'user');
        $this->Auth->userScope = array('User.status' => 1);

        $this->Auth->allow('login', 'index', 'coming_soon', 'find_most_rated', 'test_bx', 'autocompletesearch', 'tags', 'attributes', 'tag', 'subject_suggestion', 'check_login');
        $this->Auth->loginRedirect = array('controller' => 'Homes', 'action' => 'index');
    }

    function admin_register() {

        if (!empty($this->data)) {
            // Here you should validate the username (min length, max length, to not include special chars, not existing already, etc)  
            // As well as the password  

            if ($this->User->save($this->data)) {
                // Let's read the data we just inserted  
                //$data = $this->User->read();
                // Use it to authenticate the user  
                //$this->Auth->login($data);
                $aro = new Aro();
                $parent = $aro->findByAlias($this->User->find('count') > 1 ? 'User' : 'Moderator');

                $aro->create();
                $aro->save(array(
                    'model' => 'User',
                    'foreign_key' => $this->User->id,
                    'parent_id' => $parent['Aro']['id'],
                    'alias' => 'User::' . $this->User->id
                ));
                // Then redirect  
                $this->Session->setFlash('Welcome user');
                $this->redirect(array('controller' => 'Homes', 'action' => 'index'));
            }
        }
    }

    function index() {

        //debug($_POST);die();
        $this->set('title_for_layout', 'Rate The Universe');

        //including captcha class
//        $this->Captcha = new CaptchaComponent(); //creating an object instance
//        $this->Captcha->controller = & $this; //assign this conroller(CaptchaController) object to its captcha object's controller property.
//        $captcha_src = $this->Captcha->create();
//        $this->set('captcha_src', $captcha_src = $this->Captcha->create()); //create a capthca and assign to a variable
        //debug($_SESSION);        
        $randomSubjectIds = $this->Subject->find('list', array('conditions' => array('Subject.image !=' => '', 'Subject.17+' => '0', 'Subject.status' => '1'), 'fields' => 'id', 'order' => 'RAND()', 'limit' => 50));
        $subjects = $this->Subject->find('all', array('contain' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'),
            'conditions' => array('Subject.id' => $randomSubjectIds, 'Subject.image <>' => ''),
            'order' => 'RAND()'));

        $this->set('subjects', $subjects);
        /*         * ************ Set data  for content boxes in home page  ************** */
        /*
          $what_is_rtu=$this->Facts->find('first',array('conditions'=>array('Facts.alias'=>'what_is_rtu'))); // We have set alias=what_is_rtu for the content of *What is Rate The Universe ?* in database.
          $this->set('what_is_rtu',$what_is_rtu);
          $fun_facts=$this->Facts->find('first',array('conditions'=>array('Facts.alias'=>'fun_facts'))); // We have set alias=fun_facts for the content of *Fun fact* in database.
          $this->set('fun_facts',$fun_facts);
          $did_u_know=$this->Facts->find('first',array('conditions'=>array('Facts.alias'=>'did_u_know'))); // We have set alias=did_u_know for the content of *Did you know ?* in database.
          $this->set('did_u_know',$did_u_know);
         */
        /*         * ***********    Most Rated Subject Today ************ */
        $this->set('mostrated', $this->find_most_rated());

        /*         * ***********    Most Rated Subject Today Ends ************ */
    }

    function coming_soon() {
        $this->set('title_for_layout', 'Rate The Universe-Coming soon');
        $this->Captcha = new CaptchaComponent(); //creating an object instance
        $this->Captcha->controller = & $this; //assign this conroller(CaptchaController) object to its captcha object's controller property.
        $captcha_src = $this->Captcha->create();
        $this->set('captcha_src', $captcha_src = $this->Captcha->create()); //create a capthca and assign to a variable
    }

    function subscribe() {
        if ($this->RequestHandler->isAjax()) {
            $this->layout = "";
            $this->autoRender = false;
            $this->data['Newssubscriber']['email'] = $_POST['email'];
            if ($this->Newssubscriber->save($this->data)) {
                
            } else {
                if (isset($this->Newssubscriber->validationErrors['email'])) {
                    echo "email";
                }
            }
        }
    }

    function login() {
        
    }

    function logout() {

        session_destroy();
        session_unset();
        $this->redirect($this->Auth->logout());
    }

    function admin_facts() {
        $data = $this->find_most_rated();
        //debug($data);
        $data = $this->Facts->find('all');
        $this->set('facts', $data);
    }

    function admin_edit_facts($id = null) {
        if ($id) {
            $this->data = $this->Facts->read(null, $id);
        } else if (isset($this->data)) {
            $this->Facts->id = $this->data['Facts']['id'];

            if ($this->Facts->save($this->data)) {
                $this->Session->setFlash('Fact Saved');
                $this->redirect(array('controller' => 'Homes', 'action' => 'admin_facts'));
            }
        } else {
            $this->redirect(array('controller' => 'Homes', 'action' => 'facts'));
        }
    }

    function find_most_rated() {
        $result = $this->SubjectRate->find('all', array(
            'group' => array('date(SubjectRate.created)', 'SubjectRate.subject_id'),
            'joins' => array(
                array('table' => 'subject',
                    'alias' => 'Subject',
                    'type' => 'RIGHT',
                    'conditions' => array('Subject.id = SubjectRate.subject_id', 'Subject.17+' => '0', 'Subject.status' => '1')
                )
            ),
            'fields' => array('DISTINCT Subject.id', 'count(SubjectRate.subject_id) as count', 'SubjectRate.subject_id', 'Subject.image', 'Subject.subject'),
            'order' => array('SubjectRate.created DESC'),
            'limit' => '30'
                )
        );
        //debug($result);
        $mostrated = Set::sort($result, '{n}.{n}.count', 'desc');

        return $mostrated;
    }

    function test_bx() {
        $this->layout = "";
        $randomSubjectIds = $this->Subject->find('list', array('conditions' => array('Subject.image !=' => '', 'Subject.17+' => '0'), 'fields' => 'id', 'order' => 'RAND()', 'limit' => 50));
        $subjects = $this->Subject->find('all', array('contain' => array('Subject.subject', 'Subject.desc', 'Subject.id', 'Subject.image'),
            'conditions' => array('Subject.id' => $randomSubjectIds, 'Subject.image <>' => ''),
            'order' => 'RAND()'));

        $this->set('subjects', $subjects);
    }

    function autocompletesearch() {
        if ($this->RequestHandler->isAjax()) {

            //$this->autoRender=false;
        }
    }

    function tags() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            if (!isset($_GET['id'])) {
                $_GET['id'] = '2';
            }
            $this->autoRender = false;
            if (isset($_GET['id']) && $_GET['id'] != '0') {
                $tags = $this->Tag->find('all', array('conditions' => array('Tag.parent_id =' => $_GET['id'], 'Tag.type !=' => 'attribute'), 'order' => 'Tag.position asc'));
            }
            if (!empty($tags)) {
                $response['0'] = "select Tag";
            }
            $i = 0;

            foreach ($tags as $tag) {
                $response[$tag['Tag']['id']] = "" . $tag['Tag']['title'] . "";
                $i++;
            }
            $response = json_encode($response);
            echo $response;
        }
    }

    function attributes($id = null) {
        $this->layout = 'Ajax';
        /*         * ******** Initialize all variables here********* */


        /*         * *************Initialization Ends*************** */

        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            //$this->autoRender = false;
            //$this->layout='Ajax';

            $id = $_REQUEST['id'];
            $old_attrib_num = $_POST['num'];      //Number of Attribute fields already in the form.
            if ($old_attrib_num == '0') {
                $n = 0;
            } else {
                $n = ceil($old_attrib_num / 3) + 1;
            }
            $metadata = array('n' => $n, 'id' => $id);
            $data = $this->Tag->find('all', array('conditions' => array('Tag.parent_id =' => $id, 'Tag.type =' => 'attribute')));
            $this->set('attributes', $data);
            $this->set('meta', $metadata);


            //$this->render('/elements/admin_attributes');
        }
    }

    function tag() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $response = array();
            $id = '';
            $this->autoRender = false;
            $ids = array_reverse($this->get_parent_list($_POST['id']));
            // print_r($ids);
            foreach ($ids as $value) {
                $id = $id . $value['id'] . ',';
            }
            echo $id . $_POST['id'] . ',0';


            //echo '206,243,205,0';
            $response = json_encode($response);
            //echo $response;
        }
    }

    function get_parent_list($id, $result_arr = array()) {
        $tag = $this->Tag->find('first', array('conditions' => array('Tag.id =' => $id)));
        $result_arr[] = array('id' => $tag['Tag']['parent_id'], 'title' => $tag['Tag']['title']);

        if ($tag['Tag']['level'] > '2') {
            return $this->get_parent_list($tag['Tag']['parent_id'], $result_arr);
        }
        return $result_arr;
    }

    function formated_tags($title_arr, $saparater = '>') {
        $titles = '';
        $title_arr = array_reverse($title_arr);
        foreach ($title_arr as $title) {

            $titles.=$saparater . $title['title'];
        }
        return substr($titles, strlen($saparater));
    }

    function subject_suggestion() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();
            $title = $_GET['title'];
            $specifier = $_GET['specifier'];
            print_r($_REQUEST);
            die();
            $subjects = $this->Subject->find('all', array('conditions' => array('Subject.subject' => $title, 'Subject.desc' => $specifier)));

            if ($subjects) {
                return true;
            } else {
                return false;
            }
        }
    }

    function check_login() {
        if ($this->RequestHandler->isAjax()) {
            Configure::write('debug', 0);
            $this->autoRender = false;
            $response = array();

            if ($this->Auth->User('id')) {
                return true;
            } else {
                return false;
            }
        }
    }

}

?>
